#!/bin/sh

# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2019-2021 Xilinx, Inc. All rights reserved.

#
# UBUNTU NOTE
# -----------
# 1. When downgrading (say from 2.3.0 to 2.2.0) then prerm of 2.3.0 is run
#    but postinst of 2.2.0 is run. The prerm is invoked with "upgrade 2.2.0"
#    argument and postinst is invoked with "configure 2.3.0" argument.
# 2. When upgrading (say from 2.2.0 to 2.3.0) then prerm of 2.2.0 is run
#    but postinst of 2.3.0 is run. The prerm is invoked with "upgrade 2.3.0"
#    argument and postinst is invoked with "configure 2.2.0" argument.
# 3. When re-installing (say from 2.2.0 to 2.2.0) then prerm of 2.2.0 is run
#    and postinst of 2.2.0 is run. The prerm is invoked with "upgrade 2.2.0"
#    argument and postinst is invoked with "configure 2.2.0" argument.
#
# RHEL/CentOS NOTE
# ----------------
# 1. When downgrading (say from 2.3.0 to 2.2.0) then oddly postinst of 2.2.0
#    is run first followed by prerm of 2.3.0 run. The postinst is invoked with
#    "2" and prerm is invoked with "1".
# 2. When upgrading (say from 2.2.0 to 2.3.0) then prerm of 2.2.0 is NOT run
#    but postinst of 2.3.0 is run. The postinst is invoked with "2" argument.
# 3. When re-installing (say from 2.2.0 to 2.2.0) then prerm is NOT run but
#    and postinst of 2.2.0 is run. The postinst is invoked with "2" argument.

# In the case of upgrade, downgrade or re-install we would like to preserve the
# configuration of the components and hence we want to handle the configuration
# in postinst script.

OSDIST=`grep '^ID=' /etc/os-release | awk -F= '{print $2}' | tr -d '"'`
if [ [ $OSDIST == "centos" ] || [ $OSDIST == "rhel" ] ] && [ $1 -ge 1 ]; then
    echo "Cleanup is skipped for package upgrade/downgrade/re-install on RHEL/CentOS"
    exit 0
fi

OSDIST=`grep '^ID=' /etc/os-release | awk -F= '{print $2}' | tr -d '"'`
if [ $OSDIST == "ubuntu" ] && [ "$1" = "upgrade" ]; then
    echo "Unregistering old XRT Linux kernel module sources @XRT_VERSION_STRING@ from dkms on Ubuntu/Debian"
    dkms remove -m xrt -v @XRT_VERSION_STRING@ --all
    echo "Cleanup is skipped for package upgrade/downgrade/re-install on Ubuntu/Debian"
    exit 0
fi

# If we are here XRT is being uninstalled. It is NOT one of upgrade, downgrade or
# re-install.

echo "Unloading old XRT Linux kernel modules"
rmmod zocl

echo "Unregistering XRT Linux kernel module sources @XRT_VERSION_STRING@ from dkms"
dkms remove -m xrt -v @XRT_VERSION_STRING@ --all
find /lib/modules -type f -name zocl.ko -delete
find /lib/modules -type f -name zocl.ko.kz -delete
find /lib/modules -type f -name zocl.ko.xz -delete
depmod -A

rm -f /etc/udev/rules.d/10-zocl.rules

exit 0
